//
//  LCComposeViewController.swift
//  Swift0319
//
//  Created by admin on 2017/3/29.
//  Copyright © 2017年 __MyCompanyName__. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit
import WHC_KeyboardManager
import TZImagePickerController

class LCComposeViewController: LCViewController {
    
    @objc var shengJingTitle : String = String();
    @objc var notesContentStr : String = String();
    @objc var selectedData : Array<Any> = Array<Any>();

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setupUI()
    }
    private func setupUI(){
        /*******只需要在要处理键盘的界面创建WHC_KeyboardManager对象即可无需任何其他设置*******/
        let configuration = WHC_KeyboardManager.share.addMonitorViewController(self)
        /// 不要键盘头
        configuration.enableHeader = false
        /***configuration里面有丰富实用的自定义配置具体可参看代码***/

        view.backgroundColor = UIColor.white;
        edgesForExtendedLayout = UIRectEdge.init(rawValue: 0);
        tabBarController?.tabBar.isTranslucent = false;
        navigationController?.navigationBar.isTranslucent = false;
        
        let sjStr: String = self.shengJingTitle + " \n \n" + self.notesContentStr
        let shengJingMessageLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
        shengJingMessageLabel.text = sjStr
        shengJingMessageLabel.numberOfLines = 0;
        shengJingMessageLabel.textColor = redSystemColor()
        LSZSpecialPackaging.setLabel_14_5_Size(shengJingMessageLabel)

        let tempView: UIView = UIView(frame: shengJingMessageLabel.frame)
        tempView.backgroundColor = RGBColor(r: 255, g: 235, b: 235);//淡红色背景
        tempView.addSubview(shengJingMessageLabel)
        view.addSubview(tempView)
        shengJingMessageLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(5)
            make.left.equalTo(self.view).offset(5)
            make.right.equalTo(self.view).offset(-5)
            make.height.lessThanOrEqualTo(shengJingMessageLabel.snp.height)
        }

        tempView.snp.makeConstraints { (make) in
            make.top.equalTo(shengJingMessageLabel.snp.top).offset(-5)
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(shengJingMessageLabel.snp.bottom).offset(20)
        }
        tempView.isUserInteractionEnabled = true;
        tempView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(takeBackKeyboardClick(gestureRecognizer:))))
        //FIXME:- 下午4:59 添加撰写输入view
        view.addSubview(composeTextView)
        view.addSubview(composePictureView)
        
        composeTextView.snp.makeConstraints { (make) in
            make.top.equalTo(tempView.snp.bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(100)
        }
        composePictureView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.composeTextView)
            //屏蔽掉圣经上传图片
            if 屏蔽掉圣经评论上传图片 {
                make.size.equalTo(CGSize(width: 0, height: 0))
            }else{
                make.size.equalTo(CGSize(width: ScreenWidth - 20, height: ScreenWidth - 20))
            }
            make.top.equalTo(self.composeTextView).offset(150)
        }
//
        composePictureView.closeEvent = {[weak self] in
            self?.selectImage()
        }
        view.addSubview(showNumTextLabel)
        showNumTextLabel.snp.makeConstraints { (make) in
            make.right.equalTo(composeTextView.snp.right).offset(-5)
            make.top.equalTo(composeTextView.snp.bottom)
            make.width.equalTo(showNumTextLabel.snp.width)
        }
        composeTextView.utils.showNumTextLabel = showNumTextLabel
        composeTextView.utils.textFiledEditChanged(withTextField: composeTextView)

        DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute:
            {
                self.composeTextView.becomeFirstResponder()
        })
        
    }
    @objc func takeBackKeyboardClick(gestureRecognizer: UITapGestureRecognizer) {
        self.composeTextView.resignFirstResponder()
    }

    //FIXME:- 设置导航
    private func setupNav(){
        //左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
        self.setupSendButton(button)//设置按钮
        return button
    }()

    fileprivate lazy var composeTextView: LCComposeTextView = {
        let view = LCComposeTextView()
        self.setupComposeTextView(view)//设置
        return view
    }()
    fileprivate lazy var showNumTextLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.darkGray
        lab.numberOfLines = 0
        return lab
    }()

    //底部视图
    fileprivate lazy var composePictureView:LCComposePictureView = LCComposePictureView()

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
//------------------------------------------------- 按钮点击事件监听
extension LCComposeViewController :
TZImagePickerControllerDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    fileprivate func selectImage(){
        let imagePickerVc: TZImagePickerController
        imagePickerVc = TZImagePickerController(maxImagesCount: 3, delegate: self)
        imagePickerVc.allowPickingOriginalPhoto = false
//        if (self.composePictureView.imageList.count > 1) {
//            // 1.设置目前已经选中的图片数组
//            //Assets
//            imagePickerVc.selectedAssets = // 目前已经选中的图片数组
//        }
        imagePickerVc.allowPickingVideo = false
        // photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
        imagePickerVc.didFinishPickingPhotosHandle = {[weak self] (photos, assets, isSelectOriginalPhoto) -> Void in
            for image in photos! {
                self?.composePictureView.addImage(image: image)//.dealImageScale(maxWidth: 828)
            }
        }
        self.present(imagePickerVc, animated:true, completion:nil);
    }

//        let pickerVc = UIImagePickerController()
//        pickerVc.delegate = self
//        self.present(pickerVc, animated: true, completion: nil)
//    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        picker.dismiss(animated: true, completion: nil)
//        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
//            return
//        }
//        composePictureView.addImage(image: image.dealImageScale(maxWidth: 400))
//    }
}

extension LCComposeViewController:UITextViewDelegate{
    //FIXME:- 下午4:57///判断是否有值
    func textViewDidChange(_ view : UITextView){
        navigationItem.rightBarButtonItem?.isEnabled = composeTextView.hasText
    }
    //FIXME:- 下午4:57///滚动去掉第一响应
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    //FIXME:- 下午4:57///设置LCComposeTextView UITextView
    fileprivate func setupComposeTextView(_ view : LCComposeTextView){
        view.delegate = self
        //FIXME:- // 允许上下滚动
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFont(ofSize: 16)
        view.placeholder = "可发表自己对这几句的感悟、疑问、解读。"
    }
}
extension LCComposeViewController {
    //发送按钮
    fileprivate func setupSendButton(_ button: UIButton){
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        button.frame.size = CGSize(width: 40, height: 30)
        button.setTitle("发送", for: .normal)
        button.sizeToFit()
        button.setTitleColor(UIColor.lightGray, for: .disabled)
        button.setTitleColor(UIColor.white, for: .normal)
    }
    @objc fileprivate func sendAction(){

        var allText = ""
        composeTextView.attributedText.enumerateAttributes(in: NSRange(location:0,length: composeTextView.attributedText.length), options: []) { (dict, range, _) in
            allText += composeTextView.attributedText.attributedSubstring(from: range).string
        }

        print("发送按钮点击   "+allText)
        self.composePictureView.imageList.count > 0 ? upload(status: allText) : update(status: allText)

    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
        
//        getComposeText(withType: 1, shengJingTitle: shengJingTitle, notesContentArr: selectedData, success:{ (res) in
//            print(res ?? "")
//        }) { (error) in
//            print(error ?? "")
//        }
    }
    ///有图片的网络请求提交
    fileprivate func upload(status: String){
        composeUploadTextImages(withType: 1, shengJingTitle: shengJingTitle, notesContentArr: selectedData, content: status, dataImages: self.composePictureView.imageList, success: { (res) in
            print(res ?? "")
            self.cancelAction()
            SVProgressHUD.showSuccess(withStatus: "发布成功")
        }) { (error) in
            print(error ?? "")
            SVProgressHUD.showError(withStatus: "发布失败")
        }

    }
    fileprivate func update(status: String){
        composeUpdateNoImages(withType: 1, shengJingTitle: shengJingTitle, notesContentArr: selectedData, content: status, images: nil, success: { (res) in
            print(res ?? "")
            self.cancelAction()
            SVProgressHUD.showSuccess(withStatus: "发布成功")
        }) { (error) in
            print(error ?? "")
            SVProgressHUD.showError(withStatus: "发布失败")
        }

    }


}
extension LCComposeViewController {
    @objc fileprivate func cancelAction(){
        composeTextView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
}
